package com.leyou.search.service.impl;


import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.clients.ItemClient;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.search.entity.Goods;
import com.leyou.search.entity.SearchParamDTO;
import com.leyou.search.respository.GoodsRepository;
import com.leyou.search.service.SearchService;
import com.leyou.starter.elastic.entity.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.Nested;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import reactor.core.publisher.Mono;
import static com.leyou.search.constants.SearchConstants.*;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private ItemClient itemClient;


    private Goods buildGoods(SpuDTO spu) {
        // 1.自动补全的提示字段
        List<String> suggestion = new ArrayList<>(
                Arrays.asList(StringUtils.split(spu.getCategoryName(), "/")));
        suggestion.add(spu.getName());
        suggestion.add(spu.getBrandName());

        // 2.sku的价格集合
        // 2.1.查询sku集合
        List<SkuDTO> skuList = spu.getSkus();
        if (CollectionUtils.isEmpty(skuList)) {
            // 没有sku，我们去查询
            skuList = this.itemClient.querySkuBySpuId(spu.getId());
        }
        // 2.2.获取价格集合
        Set<Long> prices = skuList.stream().map(SkuDTO::getPrice).collect(Collectors.toSet());

        // 3.商品销量
        long sold = skuList.stream().mapToLong(SkuDTO::getSold).sum();

        // 4.sku的某个图片
        String image = StringUtils.substringBefore(skuList.get(0).getImages(), ",");

        // 5.规格参数
        List<Map<String, Object>> specs = new ArrayList<>();
        // 5.1.查询规格参数name和value键值对，只查询参与搜索的
        List<SpecParamDTO> params = itemClient.querySpecsValues(spu.getCid3(), true);
        // 5.2.封装
        for (SpecParamDTO param : params) {
            Map<String, Object> map = new HashMap<>(2);
            map.put("name", param.getName());
            map.put("value", chooseSegment(param));
            specs.add(map);
        }

        // 创建Goods对象，并封装数据
        Goods goods = new Goods();
        goods.setUpdateTime(new Date());
        // 自动补全的提示字段
        goods.setSuggestion(suggestion);
        // 规格参数
        goods.setSpecs(specs);
        // 商品销量
        goods.setSold(sold);
        // 商品标题
        goods.setTitle(spu.getTitle() + StringUtils.join(suggestion, " "));
        // sku的价格集合
        goods.setPrices(prices);
        // sku的某个图片
        goods.setImage(image);
        goods.setCategoryId(spu.getCid3());
        goods.setBrandId(spu.getBrandId());
        goods.setId(spu.getId());
        return goods;
    }

    private Object chooseSegment(SpecParamDTO p) {
        Object value = p.getValue();
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        if (!p.getNumeric() || StringUtils.isBlank(p.getSegments()) || value instanceof Collection) {
            return value;
        }
        double val = parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return 0;
        }
    }

    //先删除 创建索引库及其映射
    public void createIndexAndMapping() {
        // 删除已经存在的索引库
        try {
            goodsRepository.deleteIndex();
        } catch (Exception e) {
            //log.error("删除失败，可能索引库不存在！", e);
        } // 然后创建一个新的
        goodsRepository.createIndex("{\n" +
                "  \"settings\": {\n" +
                "    \"analysis\": {\n" +
                "      \"analyzer\": {\n" +
                "        \"my_pinyin\": {\n" +
                "          \"tokenizer\": \"ik_smart\",\n" +
                "          \"filter\": [\n" +
                "            \"py\"\n" +
                "          ]\n" +
                "        }\n" +
                "      },\n" +
                "      \"filter\": {\n" +
                "        \"py\": {\n" +
                "\t\t  \"type\": \"pinyin\",\n" +
                "          \"keep_full_pinyin\": true,\n" +
                "          \"keep_joined_full_pinyin\": true,\n" +
                "          \"keep_original\": true,\n" +
                "          \"limit_first_letter_length\": 16,\n" +
                "          \"remove_duplicated_term\": true\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  },\n" +
                "  \"mappings\": {\n" +
                "    \"properties\": {\n" +
                "      \"id\": {\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"suggestion\": {\n" +
                "        \"type\": \"completion\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"title\":{\n" +
                "        \"type\": \"text\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"image\":{\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": false\n" +
                "      },\n" +
                "      \"updateTime\":{\n" +
                "        \"type\": \"date\"\n" +
                "      },\n" +
                "      \"specs\":{\n" +
                "        \"type\": \"nested\",\n" +
                "        \"properties\": {\n" +
                "          \"name\":{\"type\": \"keyword\" },\n" +
                "          \"value\":{\"type\": \"keyword\" }\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}");
    }

/*    *//**
     * 把goods转换成SpuDTO
     * @param
     * @return
     *//*
    public Goods buildGoods(SpuDTO spuDTO){
        Goods goods = new Goods();
        BeanUtils.copyProperties(spuDTO,goods);
        return goods;
    }*/

    @Override
    public void loadData() {
        int page = 1, rows = 50;
        while (true) {
            log.info("开始导入第{}页数据", page);
            // 分页查询已经上架的spu
            PageDTO<SpuDTO> result = itemClient.querySpuByPage(null,null,null,page,rows,true);
            List<SpuDTO> list = result.getItems();

            // 遍历Spu集合，把SpuDTO通过buildGoods方法转为Goods
            List<Goods> goodsList = list.stream()
                    .map(this::buildGoods).collect(Collectors.toList());

            // 批量写入Elasticsearch
            goodsRepository.saveAll(goodsList);
            log.info("导入第{}页数据结束。", page);
            // 翻页
            page++;

            // 获取总页数
            Long totalPage = result.getTotalPage();
            // 判断是否还有spu没有查询（下一页是否存在）
            if (page > totalPage) {
                // 没有则结束
                break;
            }
        }

    }

    @Override
    public Mono<List<String>> getSuggest(String key) {
//        if (StringUtils.isBlank(key)) {
//            throw new LyException(400, "请求参数不能为空！");
//    }
        return goodsRepository.suggestBySingleField(SUGGESTION_FIELD,key);
    }

    @Override
    public Mono<PageInfo<Goods>> searchGoods(SearchParamDTO param) {
        //1.构建查询条件的工厂对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //1.1  source过滤
        sourceBuilder.fetchSource(DEFAULT_SOURCE_FIELD,new String[0]);
        //1.2查询条件
        QueryBuilder queryBuilder = getQueryBuilder(param);
        sourceBuilder.query(queryBuilder);
        //1.3分页条件
        sourceBuilder.from(param.getFrom());
        sourceBuilder.size(param.getSize());
        //1.4排序条件
        if (StringUtils.isNotBlank(param.getSortBy())){
            //排序字段存在，才去排序
            sourceBuilder.sort(param.getSortBy(),param.getDesc()?SortOrder.DESC:SortOrder.ASC);

        }
        //1.5高亮条件
        sourceBuilder.highlighter(new HighlightBuilder().field(DEFAULT_POST_TAG));

        //查询
        return goodsRepository.queryBySourceBuilderForPageHighlight(sourceBuilder);

    }



    @Override
    public void saveGoodsById(Long spuId) {
        //spu
        SpuDTO spu = itemClient.queryGoodsById(spuId);
        //构建goods
        Goods goods = buildGoods(spu);
        //写入索引库
        goodsRepository.save(goods);
    }

    @Override
    public void deleteGoodsById(Long spuId) {
        goodsRepository.deleteById(spuId);
    }

    private QueryBuilder getQueryBuilder(SearchParamDTO param) {
        String key = param.getKey();
        if (StringUtils.isEmpty(key)) {
            throw new LyException(400, "请求参数有误");
        }

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        //给查询构造条件添加查询条件
        boolQueryBuilder.must(QueryBuilders.matchQuery("title", key).operator(Operator.AND));


        //获取过滤条件，如果过滤条件不为空，则需要给查询构造条件，循环添加过滤条件
        Map<String, String> filters = param.getFilters();

        if (!CollectionUtils.isEmpty(filters)){

            filters.entrySet().forEach(entry->{
                String eKey = entry.getKey();
                String eValue = entry.getValue();

                if ("分类".equals(eKey)){
                    eKey = "categoryId";
                    boolQueryBuilder.filter(QueryBuilders.termQuery(eKey,eValue));
                }else if ("品牌".equals(eKey)){
                    eKey="brandId";
                    boolQueryBuilder.filter(QueryBuilders.termQuery(eKey,eValue));
                }


            });
        }
        return boolQueryBuilder;
    }


    @Override
    public Mono<Map<String, List<?>>> listFilter(SearchParamDTO searchParamDTO) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //搜索条件
        searchSourceBuilder.query(getQueryBuilder(searchParamDTO));
        //聚合条件
        searchSourceBuilder.aggregation(AggregationBuilders.terms("brandId_agg").field("brandId").size(20));

        searchSourceBuilder.aggregation(AggregationBuilders.terms("categoryId_agg").field("categoryId").size(20));

        /*searchSourceBuilder.aggregation(AggregationBuilders.nested("specAgg","specs")
        )*/

        searchSourceBuilder.aggregation(AggregationBuilders.nested("spec_agg", "specs")
                .subAggregation(AggregationBuilders.terms("name_agg").field("specs.name")
                        .subAggregation(AggregationBuilders.terms("value_agg").field("specs.value"))));
        Mono<Aggregations> aggregationsMono = goodsRepository.aggregationBySourceBuilder(searchSourceBuilder);

        return aggregationsMono.map(aggregations -> {
            Map<String, List<?>> map = new LinkedHashMap<>();

            Terms brandId_agg = aggregations.get("brandId_agg");
            List<Long> brandIds = brandId_agg.getBuckets()
                    .stream()
                    .map(bucket -> ((Terms.Bucket) bucket).getKeyAsNumber())
                    .map(Number::longValue)
                    .collect(Collectors.toList());

            Terms categoryId_agg = aggregations.get("categoryId_agg");
            List<Long> categoryIds = categoryId_agg.getBuckets()
                    .stream()
                    .map(cBucket -> ((Terms.Bucket) cBucket).getKeyAsNumber())
                    .map(Number::longValue)
                    .collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(categoryIds)) {
                map.put("分类", itemClient.queryCategoryByIds(categoryIds));
            }
            if (!CollectionUtils.isEmpty(brandIds)) {
                map.put("品牌", itemClient.queryBrandByIds(brandIds));
            }

            Nested spec_agg = aggregations.get("spec_agg");
            Terms name_agg = spec_agg.getAggregations().get("name_agg");
            name_agg.getBuckets().forEach(bucket -> {
                String nameKey = ((Terms.Bucket) bucket).getKeyAsString();
                Terms value_agg = ((Terms.Bucket) bucket).getAggregations().get("value_agg");
                List<String> valueList = value_agg.getBuckets()
                        .stream()
                        .map(valueBucket -> ((Terms.Bucket) valueBucket).getKeyAsString())
                        .collect(Collectors.toList());
                map.put(nameKey, valueList);
            });
            return map;
        });
    }



}
